package com.lbs.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Administrator
 * @date 2021/5/29 10:01
 * @description
 **/
public class JdbcUtils {

    private static ComboPooledDataSource dataSource;

    private static ThreadLocal<Connection> local = new ThreadLocal<>();

    static {
        dataSource = new ComboPooledDataSource();
    }

    public static Connection getConnection() {
        Connection connection = local.get();
        if (connection == null) {
            try {
                connection = dataSource.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            local.set(connection);
        }

        return connection;
    }

    public static void CloseAll() {
        Connection connection = local.get();
        local.remove();
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
